$.jQTouch({
    icon: 'images/brightcove.png',
    statusBar: 'black-translucent',
    preloadImages: [
        'themes/jqt/img/chevron_white.png',
        'themes/jqt/img/bg_row_select.gif',
        'themes/jqt/img/back_button_clicked.png',
        'themes/jqt/img/button_clicked.png'
        ]
});      

$(document).ready(function() {
  loadBrightcovePlaylists();
});    


function loadBrightcovePlaylists() {
  $.getJSON("/playlists.json",
    function(data){
      $.each(data.items, function(i, playlist) {

        // create the playlist item
        $(createListItemForPlaylist(playlist)).appendTo("#playlists");
        $(createPanelForPlaylist(playlist)).appendTo("body");

        // populate the list of videos for the playlist
        $.each(playlist.videos, function(j, video) {
          if (isNewH264Video(video)) {
            $(createVideoListItem(video)).appendTo("#items" + playlist.id);
  
            if (isNewVideoOnPage(video)) {

              // create the video tag for a selected video.
              $(createPanelForVideo(video)).appendTo("body");
              $(createPlayerForVideo(video)).appendTo("#" + video.id);
            }
          }
        });

      });
      return false;
    });    
}

function isNewVideoOnPage(video) {
  return $("#" + video.id).length == 0;
}

function isNewH264Video(video) {
  return video && 
      video.videoFullLength && 
      video.videoFullLength.videoCodec == "H264";
}

function createPanelForPlaylist(playlist) {
  return $.sprintf(
      "<div id='%(id)d'>" +
        "<div class='toolbar'>" +
          "<h1>%(name)s</h1>" + 
          "<a class='back' href='#'>Home</a>" +
        "</div>" +
        "<ul id='items%(id)d'></ul>" +
      "</div>",
      {id: playlist.id, name: playlist.name});
}

function createListItemForPlaylist(playlist) {
  return $.sprintf(
      "<li class='arrow'>" +
        "<a href='#%(id)d'>%(name)s</a>" +
      "</li>", 
      {id: playlist.id, name: playlist.name});
}

function createVideoListItem(video) {
  return $.sprintf(
      "<li class='arrow title' id='video%(id)d'>" +
        "<a href='#%(id)d'>" +
          "<img src='%(thumbnailURL)s' class='thumbnail'/>" +
          "<span class='title'>%(name)s</span>" +
        "</a>" +
      "</li>",
      {id: video.id, name: video.name, thumbnailURL: video.thumbnailURL});
}

function createPanelForVideo(video) {
  return $.sprintf(
      "<div id='%(id)d'>" + 
        "<div class='toolbar'>" +
          "<h1>%(name)s</h1>" + 
          "<a class='back' href='#'>Back</a>" +
        "</div>" +
      "</div>",
      {id: video.id, name: video.name});
}

function createPlayerForVideo(video) {
  return $.sprintf(
      "<video class='player' controls='controls' src='%(url)s'></video>",
      {url: video.FLVURL});
}
